package org.bluedream.core.module.login.controller;


import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.session.Session;
import org.apache.shiro.web.util.WebUtils;
import org.bluedream.comm.base.BaseController;
import org.bluedream.comm.utils.EmptyUtil;
import org.bluedream.core.config.exception.LicenseNullException;
import org.bluedream.core.config.exception.OrgNotPermitException;
import org.bluedream.core.config.exception.OrgNullPointException;
import org.bluedream.core.module.login.service.LoginService;
import org.bluedream.core.module.sys.entity.Organization;
import org.bluedream.core.module.sys.service.OrganizationService;
import org.bluedream.core.utils.UserUtil;
import org.bluedream.core.utils.YmlRead;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "${adminPath}")
public class LoginController extends BaseController {
    @Resource
    private LoginService loginService;

    @Resource
    private OrganizationService organizationService;

    private String getQueryString(HttpServletRequest request){
        String queryString = request.getQueryString();
        return queryString == null ? "" : "?" + queryString;
    }

    @RequestMapping(
            value = {"/login"}
    )
    public String login(HttpServletRequest request,  Model model){
        if (StringUtils.containsIgnoreCase(request.getRequestURI() , ";JSESSIONID=")){
            return "redirect:" + this.adminPath + "/login" + getQueryString(request);
        }
        Object loginInfo = UserUtil.getSubject().getPrincipal();
        if (EmptyUtil.isNoEmpty(loginInfo)){
            return index(model);
        }else {
            String exceptionClassName = (String)request.getAttribute("shiroLoginFailure");
            String error = null;
            if (UnknownAccountException.class.getName().equals(exceptionClassName)){
                logger.error("无此用户！");
                error = "用户名或密码错误";
            }else if (IncorrectCredentialsException.class.getName().equals(exceptionClassName)){
                logger.error("登录密码错误");
                error = "用户名或密码错误";
            }else if (OrgNotPermitException.class.getName().equals(exceptionClassName)){
                logger.error("登录组织没有授权");
                error = "登录组织没有授权";
            }else if (OrgNullPointException.class.getName().equals(exceptionClassName)){
                logger.error("登录组织不能为空");
                error = "登录组织不能为空";
            }else if (LicenseNullException.class.getName().equals(exceptionClassName)){
                logger.error("系统未经授权，请联系系统管理员！");
                error = "系统未经授权，请联系系统管理员！";
            }else if (exceptionClassName != null){
                logger.error("其他错误：" + exceptionClassName);
                error = "其他错误：" + exceptionClassName;
            }
            model.addAttribute("error" , error);
            model.addAttribute("productName" , YmlRead.getValueToString("productName"));
            model.addAttribute("productVersion" , YmlRead.getValueToString("productVersion"));
            model.addAttribute("devCompany" , YmlRead.getValueToString("devCompany"));
            return "sysLogin";
        }
    }

    @RequestMapping(value = "/index")
    public String index(Model model){
        List<Map<String , Object>> treeData = loginService.menuTreeData();
        model.addAttribute("loginUser" , UserUtil.getLoginInfo());
        model.addAttribute("loginOrg" , UserUtil.getLoginOrgName());
//        model.addAttribute("basePath" , this.adminPath);
        model.addAttribute("menuTreeData" , treeData);
        return "index";
    }

    @RequestMapping("/orgTreeData")
    @ResponseBody
    public List<Map<String , Object>> treeData(@RequestParam(defaultValue="1")String isShowCode , @RequestParam(defaultValue="undefined")String excludeCode){
        return organizationService.treeData(excludeCode , isShowCode , (List<Organization>) null);
    }

}
